use axum::{extract::Request, http::HeaderValue, middleware::Next, response::Response};
use tracing::warn;

use super::REQUEST_ID_HEADER;

pub async fn set_request_id(mut req: Request, next: Next) -> Response {
    // if x-request-id exists,do nothing otherwise generate  a new one
    let request_id = match req.headers().get(REQUEST_ID_HEADER) {
        Some(id) => Some(id.clone()),
        None => {
            let request_id = uuid::Uuid::now_v7().to_string();
            let id: Option<HeaderValue> = match HeaderValue::from_str(&request_id) {
                Ok(v) => {
                    req.headers_mut().insert(REQUEST_ID_HEADER, v.clone());
                    Some(v)
                }
                Err(e) => {
                    warn!("parse generated request id error:{:?}", e);
                    None
                }
            };
            id
        }
    };
    let mut resp = next.run(req).await;
    let Some(id) = request_id else { return resp };
    resp.headers_mut().insert(REQUEST_ID_HEADER, id);
    resp
}
